package com.cskaoyan.day03.queue;

/**
 * @author stone
 * @date 2022/01/29 15:12
 */
public class LinkedQueue<T> {
    private int size;
    private Node head;
    private Node rear;

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    //从rear进
    public boolean offer(T value) {
        if (isEmpty()) {
            head = new Node(value);
            rear = head;
        }else {
            rear.next = new Node(value);
            rear = rear.next;
        }
        size++;
        return true;
    }

    //从head出
    public T poll() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空！");
        }
        T value = head.value;
        if (size == 1) {
            head = null;
            rear = null;
        } else {
            head = head.next;
        }
        size--;
        return value;
    }

    public T peek() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空！");
        }
        return head.value;
    }


    class Node{
        T value;
        Node next;

        public Node(T value, Node next) {
            this.value = value;
            this.next = next;
        }

        public Node(T value) {
            this.value = value;
        }
    }
}
